﻿<%@ WebHandler Language="C#" Class="detail" %>
using System;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Web.Configuration;
using Models;
using System.Linq;
public class detail : IHttpHandler {


    public static string APPID =WebConfigurationManager.AppSettings["APPID"];
    public static string APPSECRET =WebConfigurationManager.AppSettings["APPSECRET"];
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        var js_code=HttpContext.Current.Request.QueryString["code"];

        if (string.IsNullOrEmpty(js_code))
        {
            HttpContext.Current.Response.Write("parameter error");
            return;
        }
        string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=" +APPID+ "&secret=" +APPSECRET+ "&js_code=" + js_code + "&grant_type=authorization_code";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
        request.Method = "GET";
        request.ContentType = "text/html;charset=utf-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();
        var mybacktoken = JObject.Parse(retString);
        var authtoken=mybacktoken["openid"].ToString();

        var access_token=mybacktoken["session_key"].ToString();
        var user_id=mybacktoken["openid"].ToString();


        var code=0;
        using (Entities bll = new Entities())
        {
            var wxuser = bll.User.FirstOrDefault(p => p.UOpenID == authtoken);
            if (wxuser==null) //没有这个用户
            {
                wxuser = new User();
                wxuser.UGuid = _rky.GenerateStringID();
                wxuser.UOpenID = authtoken;
                wxuser.Ustate = 0;
                wxuser.Ujifen = 0;
                wxuser.RegTime = DateTime.Now;
                wxuser.isMember = 0;  //直
                bll.User.Add(wxuser);
                bll.SaveChanges();


            }
            var data = new
            {
                userinfo=wxuser,
                data=new{access_token,user_id},
                code,
                msg = "获取session_key",
                time = DateTime.Now
            };

        Formatting microsoftDataFormatSettings = default(Formatting);
        string result = JsonConvert.SerializeObject(data, microsoftDataFormatSettings);

        context.Response.Write(result);

    }

    HttpContext.Current.Response.End();
        //context.Response.Write("Hello World");


    }





public bool IsReusable {
    get {
        return false;
    }
}

}